<template>
  <div class="min-h-screen flex items-center justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
    <div class="max-w-md w-full space-y-8 bg-white p-8 rounded-lg shadow-md">
      <!-- 标题区域 -->
      <div class="text-center">
        <h1 class="text-2xl font-bold text-gray-900">找回密码</h1>
        <p class="mt-2 text-sm text-gray-600">请输入您的注册邮箱，我们将向您发送验证码</p>
      </div>

      <!-- 重置密码表单 -->
      <el-form
        ref="resetForm"
        :model="formData"
        :rules="rules"
        class="mt-8 space-y-6"
        @submit.prevent="handleSubmit"
      >
        <!-- 邮箱 -->
        <el-form-item prop="email">
          <el-input
            v-model="formData.email"
            placeholder="请输入邮箱"
            type="email"
            prefix-icon="Message"
          />
        </el-form-item>

        <!-- 验证码 -->
        <el-form-item prop="code">
          <div class="flex items-center space-x-2">
            <el-input
              v-model="formData.code"
              placeholder="请输入6位验证码"
              class="flex-1"
              maxlength="6"
              @input="formData.code = formData.code.replace(/[^\d]/g, '')"
            />
            <el-button 
              type="primary" 
              :disabled="cooldown > 0" 
              @click="sendVerificationCode"
              class="w-32 whitespace-nowrap"
            >
              {{ cooldown > 0 ? `${cooldown}秒后重发` : '获取验证码' }}
            </el-button>
          </div>
        </el-form-item>

        <!-- 新密码 -->
        <el-form-item prop="newPassword" v-if="step === 2">
          <el-input
            v-model="formData.newPassword"
            placeholder="请输入新密码"
            type="password"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>

        <!-- 确认新密码 -->
        <el-form-item prop="confirmPassword" v-if="step === 2">
          <el-input
            v-model="formData.confirmPassword"
            placeholder="请确认新密码"
            type="password"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item>
          <el-button
            type="primary"
            native-type="submit"
            class="w-full py-2 px-4 text-white rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500"
            :loading="loading"
          >
            {{ step === 1 ? '验证' : '重置密码' }}
          </el-button>
        </el-form-item>

        <!-- 返回登录 -->
        <div class="text-center mt-4">
          <router-link to="/login" class="inline-flex items-center text-sm text-primary-600 hover:text-primary-500">
            <el-icon class="mr-1"><ArrowLeft /></el-icon>
            返回登录页
          </router-link>
        </div>
      </el-form>

      <!-- 操作提示 -->
      <div class="mt-6" v-if="resetSuccess">
        <el-alert
          title="密码重置成功"
          type="success"
          description="您的密码已成功重置，请使用新密码登录。"
          show-icon
          :closable="false"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, watch, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Message, ArrowLeft, Lock } from '@element-plus/icons-vue'
import { formRules } from '../utils/validate'
import { useUserStore } from '../store'

const router = useRouter()
const userStore = useUserStore()

// 表单引用
const resetForm = ref(null)

// 状态
const loading = ref(false)
const cooldown = ref(0)
const step = ref(1) // 1: 验证码步骤, 2: 重置密码步骤
const resetSuccess = ref(false)
let cooldownTimer = null

// 表单数据
const formData = reactive({
  email: '',
  code: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const rules = reactive({
  email: formRules.email,
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码为6位数字', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应为6-20个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
})

// 验证确认密码
function validateConfirmPassword(rule, value, callback) {
  if (value !== formData.newPassword) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

// 发送验证码
async function sendVerificationCode() {
  if (cooldown.value > 0) return
  
  try {
    // 验证邮箱
    await resetForm.value.validateField('email')
    
    // 发送验证码
    loading.value = true
    
    // 模拟API调用
    setTimeout(() => {
      ElMessage.success(`验证码已发送到邮箱: ${formData.email}`)
      startCooldown()
      loading.value = false
    }, 1000)
  } catch (error) {
    console.error('发送验证码失败:', error)
    loading.value = false
  }
}

// 开始倒计时
function startCooldown() {
  cooldown.value = 60
  cooldownTimer = setInterval(() => {
    cooldown.value--
    if (cooldown.value <= 0) {
      clearInterval(cooldownTimer)
    }
  }, 1000)
}

// 清除定时器
watch(() => cooldown.value, (newVal) => {
  if (newVal <= 0 && cooldownTimer) {
    clearInterval(cooldownTimer)
  }
})

// 提交表单
async function handleSubmit() {
  try {
    if (step.value === 1) {
      // 验证邮箱和验证码
      await resetForm.value.validateField(['email', 'code'])
      
      // 设置加载状态
      loading.value = true
      
      // 模拟验证码验证
      setTimeout(() => {
        // 验证成功，进入下一步
        step.value = 2
        loading.value = false
      }, 1000)
    } else {
      // 验证所有字段
      await resetForm.value.validate()
      
      // 设置加载状态
      loading.value = true
      
      // 模拟重置密码
      setTimeout(() => {
        resetSuccess.value = true
        ElMessage.success('密码重置成功')
        
        // 3秒后跳转到登录页
        setTimeout(() => {
          router.push('/login')
        }, 3000)
        
        loading.value = false
      }, 1500)
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error(error.message || '操作失败，请稍后重试')
    loading.value = false
  }
}

// 组件卸载时清除定时器
onBeforeUnmount(() => {
  if (cooldownTimer) {
    clearInterval(cooldownTimer)
  }
})
</script>